<template>
    <section class="lix-event-wran-detail-main">
        <div class="flex-direction-column main-left">
            <div class="left-title-wrap">
                <areaTitle :title="$t('异常监控')" />
                <ul class="tab-ul">
                    <li v-for="(camera, i) in cameraWarnList" :key="i"
                        :class="['tab-item', { 'active': activeCamera === camera._id }]">
                        <span>{{ camera.alias || '工位' + i }}</span>
                    </li>
                </ul>
                <a class="back-home" @click="goHome()">
                    <SvgIcon icon-class="back_home_icon" />
                    <span>{{ $t('返回主页') }}</span>
                </a>
            </div>
            <div class="card-border camera-view-wrap">
                <centerViewCameraDetail :isReadly="completeInit" />
            </div>
        </div>
        <div class="flex-direction-column main-right">
            <div class="flex-direction-column right-top">
                <areaTitle :title="$t('待处理事件')" />
                <DataGatheringList ref="warnVideoListDom" :cameraIp="activeCamera" @getVideoRow="getVideoRow" />
            </div>
            <div class="flex-direction-column right-bottom">
                <areaTitle :title="$t('告警处置')" />
                <div class="card-border flex-direction-column event-handle">
                    <button class="btn btn-error" @click="confirmedCameraEvent()">
                        <span>
                            <SvgIcon icon-class="warn_sure_icon" />
                            {{ $t('批量告警确认') }}
                        </span>
                    </button>
                </div>
            </div>
        </div>
    </section>

    <videoPreviewDialog v-model:video-dialog-visible="videoDialogVisible" :video-url="videoUrl" :img-list="phoneImgList"
        :renderVideo="dialogRenderVideo" :camera-results="cameraResultsTxt" :playStartTime="videoStartTime" />

</template>
<script setup lang="ts">

import type {
    // T_SocketPipelineData,
    T_SocketPipelineWarnReason,
} from './types'

import {
    socketIoClientInstance
} from '@/data-services/socket-io-1'

import {
    T_RectGraphResultItem,
    T_Camera_Video_Row,
    T_Device_ClientSide_Cam_NodeDetails,
    T_SocketPipelineMovementData,
} from '../components/types.ts'

import {
    REASON_CODE_HAT,
    REASON_CODE_PHONE,
    CAMERA_STREAM_ID,
    formatStreamIdList,
    getKonvaListOfGroup,
} from '@/utils'

import type {
    T_DeviceBindSearch,
    T_PipelinesListItem,
} from '@/data-services/api/types'

import areaTitle from '@/pages/components/area-title.vue'

import {
    GetEquipments_CameraList,
    // GetDevicesVideoList,
    getSingleCamera_RtspFullUri,
    xmeDSIC_Solutions_GetDevicesBind,
} from '@/data-services/api/index'

import {
    cameraWarnConfig,
    useStore_ViewportsGrid_Detail,
} from '@/pages/pinia'
const vsp_ViewportsGrid = useStore_ViewportsGrid_Detail()
const cameraWarnListStore = cameraWarnConfig()

import { i18n } from '@/vue-i18n'

import { useRoute } from 'vue-router'
import router from '@/vue-router'

import appEnvironment from '@/app-environments'
import axios from 'axios'


const {
    networkHosts: {
        apiServer1: {
            fullHost,
        },
    },
} = appEnvironment

const $t = i18n.global.t

const completeInit = ref(false)
const videoDialogVisible = ref(false)

const activeCamera = ref('')
const warnVideoListDom = ref()
const route = useRoute()

const phoneImgList = ref<Array<string>>([])
const dialogRenderVideo = ref(true)
const videoStartTime = ref(0)
const videoUrl = ref('')
const cameraWarnList = ref<T_Device_ClientSide_Cam_NodeDetails[]>([])

const cameraViewData = ref<T_Device_ClientSide_Cam_NodeDetails[]>([])
const pipelinesData = ref<T_PipelinesListItem[]>([])
// const cameraVideoList = ref<T_Camera_Video_Row[]>([])
// const videoRectList   = ref<T_Device_ClientSide_Cam_VideoRect[]>([])
const cameraResultsTxt = ref<T_RectGraphResultItem[]>([])

const pageConfigCamera = reactive({
    pageSize: 20,
    pageNumber: 0,
    totalCamera: 0,
})

const pageConfigBindCard = reactive({ // 已绑定卡片页参数
    pageSize: 20,
    currentPageNaum: 0,
    totalPipelines: 0,
    allPageNum: 0,
})

async function getCameraList(paginationPageIndex?: number): Promise<void> {

    const params = {
        entriesPerPage: pageConfigCamera.pageSize,
        pageNumber: paginationPageIndex === undefined ? pageConfigCamera.pageNumber : paginationPageIndex,
        condition: { ...{ device_type: 1 } },
    }
    return GetEquipments_CameraList(params).then(async (res) => {
        if (res && res.code == 0) {
            const {
                devicesList, totalDevices,
            } = res.data
            cameraViewData.value = devicesList || []
            pageConfigCamera.totalCamera = totalDevices
            cameraViewData?.value?.forEach((camera) => {
                const sortNum = camera.alias && camera.alias.match(/\d+/g)
                if (sortNum?.length) {
                    camera.sortNum = +sortNum[0]
                }
                if (!camera.konvaConfigMap) {
                    camera.konvaConfigMap = new Map()
                    camera.konvaConfigMap.set(CAMERA_STREAM_ID, { configKonvaList: [], })
                }
                if (!camera.konvaConfigRois) {
                    camera.konvaConfigRois = new Map()
                }
                camera.helmetStatus = {
                    isWarning: false
                }
                camera.phoneStatus = {
                    isWarning: false
                }
            })

            cameraViewData.value = cameraViewData?.value?.sort((a, b) => {
                return ((a.sortNum || 0) - (b.sortNum || 0))
            })

            if (cameraViewData.value) {
                await getBindDevice()
                const currentIp = route.query.id
                activeCamera.value = currentIp as string

                const urlList = await getSingleCamera_RtspFullUri(activeCamera.value)
                const currentCamera = cameraViewData.value.filter(cam => cam._id === currentIp)
                if (currentCamera.length) {
                    currentCamera[0].currentRtspUri = `/whep/endpoint/${urlList[0]}`
                    const cameraBindList = pipelinesData.value.filter(item => item.cameraList.includes(activeCamera.value))
                    const pipelinesOption = cameraBindList.map(bind => {
                        return {
                            label: bind.bindName || '',
                            value: bind._id,
                        }
                    }) || []
                    const defaultOptions = [{
                        label: '- -',
                        value: '',
                    }]
                    currentCamera[0].pipelineIds = [...defaultOptions, ...pipelinesOption]
                    currentCamera[0].currentPipelineId = currentCamera[0].pipelineIds[currentCamera[0].pipelineIds.length - 1].value
                    currentCamera[0].streamList = formatStreamIdList()
                    currentCamera[0].currentStreamId = currentCamera[0].streamList[currentCamera[0].streamList.length - 1].value
                    cameraWarnList.value = currentCamera
                }
            }
        }
    }).catch(error => {
        console.log('获取相机列表api异常==', error)
    })
}

function assignCamerasToAllViewports_EachForEach(
    camerasList: Array<T_Device_ClientSide_Cam_NodeDetails>
): void {
    if (!Array.isArray(camerasList)) { camerasList = [] }
    completeInit.value = false
    vsp_ViewportsGrid.statesOfAllViewports.forEach((stateOfCertainViewport, arrayIndex) => {
        const {
            viewportIndex,
        } = stateOfCertainViewport

        const cameraAsContentSource = camerasList[arrayIndex]

        if (cameraAsContentSource) {
            cameraAsContentSource.name = cameraAsContentSource.alias ? `${cameraAsContentSource.alias}(${cameraAsContentSource._id})` : cameraAsContentSource._id
            vsp_ViewportsGrid.assignContentSourceToViewport({
                viewportIndex,
                contentSource: {
                    contentSourceId: cameraAsContentSource._id!,
                    contentSourceDetails: cameraAsContentSource,
                },
            })
        }
    })
    nextTick(() => {
        completeInit.value = true
    })
}

async function getBindDevice(seachBindData?: T_DeviceBindSearch) {
    const params = {
        entriesPerPage: pageConfigBindCard.pageSize,
        pageNumber: pageConfigBindCard.currentPageNaum,
        condition: { ...seachBindData },
    }
    try {
        const res = await xmeDSIC_Solutions_GetDevicesBind(params)
        const {
            data: {
                pipelinesList,
                totalPipelines,
            },
        } = res
        pageConfigBindCard.totalPipelines = totalPipelines || 0
        pageConfigBindCard.allPageNum = Math.ceil(totalPipelines / pageConfigBindCard.pageSize)
        pipelinesData.value = pipelinesList || []
    } catch (error) {
        console.log('获取设备绑定关系api失败：', error)
    }
}

async function confirmedCameraEvent() {
    await warnVideoListDom.value.submitConfirmed()
}

// async function resetedCameraEvent() {
//    await warnVideoListDom.value.submitReseted()
// }
const videoCameraIp = ref('')

async function getVideoRow(videoRow: T_Camera_Video_Row): Promise<void> {
    dialogRenderVideo.value = true
    videoUrl.value = videoRow.video_url ? fullHost + videoRow.video_url : ''
    videoCameraIp.value = videoRow.addr
    videoStartTime.value = videoRow.video_start || 0
    await axios.get(fullHost + '/auto_record/' + videoRow.overlay).then(res => {
        cameraResultsTxt.value = res.data || []
    }).catch(error => {
        console.log(error)
    })
    videoDialogVisible.value = true
}

function goHome() {
    router.replace({
        name: 'Index',
    })
}

onMounted(async () => {
    await getCameraList()
    /** 监听相机列表检测结果 */
    socketIoClientInstance.on('inference/u-yolo/raw', (data: T_SocketPipelineMovementData) => {
        if (data && (data instanceof Object)) {
            vsp_ViewportsGrid.statesOfAllViewports.forEach((stateOfCertainViewport) => {
                const {
                    contentSource,
                } = stateOfCertainViewport
                const batched_results = data.batched_results
                if (contentSource && batched_results && batched_results.length) {
                    batched_results.forEach(item => {
                        const sourceDetails = contentSource.contentSourceDetails as unknown as T_Device_ClientSide_Cam_NodeDetails
                        if (item.camera_id === sourceDetails._id && item.results) {
                            let configMapVal = sourceDetails.konvaConfigMap?.get(CAMERA_STREAM_ID)
                            if (sourceDetails && configMapVal) {
                                configMapVal.configKonvaList = getKonvaListOfGroup(item) || []
                            }
                        }
                    })
                }
            })
            // console.log('vsp_ViewportsGrid.statesOfAllViewports', vsp_ViewportsGrid.statesOfAllViewports)
        }
    })

    socketIoClientInstance.on('xdxk_record_ack', (data: T_SocketPipelineWarnReason) => {
        // 相机上报事件  更改相机报警状态
        if (data && (data instanceof Object)) {
            if (activeCamera.value === data.addr) {
                nextTick(() => {
                    warnVideoListDom.value && warnVideoListDom.value.getVideoList()
                })
            }
            // console.log('lx_shizhi_record_ack', data)
            // cameraViewData.value?.forEach((ele) => {
            //     if(ele._id === data.addr) {
            //         ele.isWarning = true
            //     }
            // })

            // cameraWarnList.value = getCameraWarnList(cameraViewData.value)
            // console.log('socket-cameraWarnList', cameraWarnList.value)
            // if(!activeCamera.value && cameraWarnList.value && cameraWarnList.value[0]) {
            //     activeCamera.value = cameraWarnList.value[0]._id
            //     setCameraViewData(cameraWarnList.value[0])
            // }
        }
    })

    // await setCameraStatusHelmet()
    // await setCameraStatusPhone()
    // cameraWarnList.value = getCameraWarnList(cameraViewData.value)

    if (cameraWarnList.value && cameraWarnList.value.length) {
        const oneCamera = cameraWarnList.value[0]
        activeCamera.value = route.query.id as string
        let viewData = cameraWarnList.value.filter(item => item._id === route.query?.id)
        if (!viewData.length) {
            viewData = [oneCamera]
            activeCamera.value = oneCamera._id
        }
        assignCamerasToAllViewports_EachForEach(viewData)
    }
})

onUnmounted(() => {
    socketIoClientInstance.off('device-stream-list')
    socketIoClientInstance.off('xdxk_record_ack')
})

// function setCameraViewData(camera: T_Device_ClientSide_Cam_NodeDetails){
//     activeCamera.value = camera._id
//     cameraViewData!.value![0] = camera
//     assignCamerasToAllViewports_EachForEach( cameraViewData.value )
// }

// function getCameraWarnList(cameraList: T_Device_ClientSide_Cam_NodeDetails[]) : Array<T_Device_ClientSide_Cam_NodeDetails>{
//     const warnListAll = cameraList.filter(item => item.isWarning || item.helmetStatus?.isWarning || item.phoneStatus?.isWarning)
//     console.log('warnListAll', warnListAll)
//     if(warnListAll && warnListAll.length) {
//         let warnList      = warnListAll.reduce((cam:T_Device_ClientSide_Cam_NodeDetails[], current) => {
//             const camItem = cam.find(item => item._id === current._id)
//             const sortNum = current.alias && current.alias.match(/\d+/g)
//             if(sortNum?.length) {
//                 current.sortNum = +sortNum[0]
//             }
//             if(!camItem) {
//                 return cam.concat(current)
//             } else {
//                 return cam
//             }
//         }, [])
//         warnList = warnList.sort((a, b) => {
//             return ((a.sortNum || 0) - (b.sortNum || 0))
//         })
//         return warnList
//     }
//     return []
// }
// async function setCameraStatusHelmet() {
//     if(cameraViewData.value && cameraViewData.value.length) {
//         await Promise.all(cameraViewData.value.map(async(cam, i) => {
//             if(!cam.online) return
//             const params = {
//                 camera_id: cam._id,
//                 confirmed: false,
//             }
//             const res = await cameraWarnListStore.getWarnStatistics(params)
//             if(res && res.data && cameraViewData.value) {
//                 if(res.data.totalRecords){
//                     cameraViewData.value[i].helmetStatus.isWarning = true
//                 }
//             } 
//         }))
//     }
// }

// async function setCameraStatusPhone() {
//     if(cameraViewData.value && cameraViewData.value.length) {
//         await Promise.all(cameraViewData.value.map(async(cam, i) => {
//             if(!cam.online) return
//             const params = {
//                 camera_id: cam._id,
//                 reason_code: REASON_CODE_PHONE,
//                 confirmed: false,
//             }
//             const res = await cameraWarnListStore.getWarnStatistics(params)
//             if(res && res.data && cameraViewData.value) {
//                 if(res.data.totalRecords){
//                     cameraViewData.value[i].phoneStatus.isWarning = true
//                 }
//             }
//         }))
//     }
// }

</script>
<style lang="scss">
@use '@/assets/style/button.scss';

.lix-event-wran-detail-main {
    display: flex;
    width: 100%;
    height: 100%;
    padding: 12px 29px;

    .camera-view-wrap {
        flex: 1;
        display: flex;
        align-items: center;
        padding: 10px;
    }

    .main-left,
    .main-right {
        height: 100%;
    }

    .main-left {
        flex: 1 1 auto;
        margin-right: 14px;

        .left-title-wrap {
            flex: 0;
            position: relative;
            display: flex;
            flex-direction: row;
            flex-wrap: nowrap;
            align-items: flex-end;
            gap: 10px;

            .lix-shizhi-area-title {
                flex: inherit;
                flex-wrap: nowrap;
                white-space: nowrap;
            }

            .tab-ul {
                display: flex;
                flex: 1;
                flex-wrap: nowrap;
                gap: 6px;

                .tab-item {
                    position: relative;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    min-width: 100px;
                    padding: 0 12px;
                    height: 36px;
                    flex-shrink: 0;
                    color: #FFF;
                    text-align: center;
                    font-size: 15px;
                    font-weight: 400;
                    cursor: auto;
                    background-image: linear-gradient(180deg, rgba(255, 201, 8, .4) 0%, rgba(63, 60, 0, .4) 100%);

                    &.active {
                        background-image: linear-gradient(180deg, #FABD16 0%, #705000 100%);

                        &::before {
                            position: absolute;
                            top: -5px;
                            left: 0;
                            content: "";
                            width: 100%;
                            height: 3px;
                            background-color: #FABD16;
                        }
                    }
                }
            }

            .back-home {
                display: flex;
                align-items: center;
                gap: 8px;
                padding-bottom: 12px;
                color: #FFF;
                font-family: Inter;
                font-size: 20px;
                font-style: normal;
                font-weight: 400;
                line-height: normal;
                cursor: pointer;

                .svg-icon {
                    width: 0.8rem;
                    height: 0.8rem;
                    margin-top: 3px;
                }

                &:hover {
                    color: #FFF9;
                }
            }
        }
    }

    .main-right {
        flex: 0 0 550px;

        .right-top {
            display: flex;
            flex: 1;
            overflow: hidden;

            .lix-shizhi-area-title {
                background: url(/src/assets/icons/svg/lix-shizhi-area-title-line-max.svg) left bottom no-repeat;
            }

            .card-border {
                padding: 14px 20px;
            }

            .router-btn {
                display: flex;
                gap: 20px;
            }

            .phone-photo {
                flex: 2;

                .router-btn {
                    flex-wrap: wrap;

                    .btn {
                        flex-basis: calc(50% - 20px);
                    }
                }
            }

            .safety-hat {
                flex: 1;
                margin-left: 30px;

                .router-btn {
                    flex-direction: column;

                    .btn {
                        width: 99%;
                        ;
                    }
                }
            }

            .sub-title {
                display: flex;
                align-items: center;
                gap: 10px;
                margin-bottom: 16px;
                color: #FFF;
                text-shadow: 0px 0.5px 0px #B6B0A8;
                font-size: 24px;
                font-style: normal;
                font-weight: 400;
                line-height: normal;

                .svg-icon {
                    width: 1.5rem;
                    height: 1.5rem;
                }
            }

        }

        .right-bottom {
            flex: 0;
            margin-top: 18px;
        }

        .event-handle {
            flex: 1;
            gap: 21px;
            align-items: center;
            justify-content: center;
            padding: 36px 10px;

            .btn {
                width: 80%;
            }
        }
    }

    .card-border {
        border-radius: 10px;
        border: 1px solid #7E7DA3;
        background: #000E3E;
    }
}
</style>